import 'dart:convert';

import 'package:crypto/crypto.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:kkhousekeep/config/constant.dart';
import 'package:kkhousekeep/net/me_account_connect.dart';
import 'package:kkhousekeep/net/respnse_code.dart';
import 'package:kkhousekeep/tools/dialog_util.dart';
import 'package:kkhousekeep/tools/shared_preferences.dart';
import 'package:kkhousekeep/tools/toast_util.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SetPasswordController extends GetxController {
  var username = "".obs;
  var oldPassword = "".obs;
  var newPassword = "".obs;
  var newPasswordConfirm = "".obs;
  var isAsh = true.obs;
  var pwdRegExp = RegExp(r"(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$");
  TextEditingController oldPwdController = TextEditingController();
  TextEditingController newPwdController = TextEditingController();
  TextEditingController newPwdConfirmController = TextEditingController();
  late MeAccountConnect _meAccountConnect;

  @override
  void onInit() {
    _meAccountConnect = Get.put(MeAccountConnect());
    oldPwdController.addListener(() {
      observeText();
    });
    newPwdController.addListener(() {
      observeText();
    });
    newPwdConfirmController.addListener(() {
      observeText();
    });
    SharedPreferences.getInstance()
        .getUserName()
        .then((value) => username.value = value);
    super.onInit();
  }

  void checkAndSave() {
    if (newPwdController.text.toString() !=
        newPwdConfirmController.text.toString()) {
      ToastUtils.showToast(tip: "密码不一致");
      return;
    }

    if (!pwdRegExp.hasMatch(newPwdController.text)) {
      ToastUtils.showToast(tip: "新密码需由6位英文+数字组合");
      return;
    }
    String oldPwd = oldPwdController.text;
    String newPwd = newPwdController.text;
    String encryptedOldPwd = md5
        .convert(utf8.encode("$oldPwd${Constant.pwdKey}"))
        .toString()
        .substring(0, 32);
    String encryptedNewPwd = md5
        .convert(utf8.encode("$newPwd${Constant.pwdKey}"))
        .toString()
        .substring(0, 32);
    modifyPassword(encryptedOldPwd, encryptedNewPwd);
  }

  Future<void> modifyPassword(
      String encryptedOldPwd, String encryptedNewPwd) async {
    var response = await _meAccountConnect.modifyPasswordForProperty(
        oldPassword: encryptedOldPwd, newPassword: encryptedNewPwd);
    if (response == null) {
      return;
    }
    if (response.code == ResponseCode.success) {
      ToastUtils.showToast(tip: "修改成功");
      Get.back();
    } else {
      DialogUtil.showNetworkFail();
    }
  }

  void observeText() {
    if (oldPwdController.text.length >= 6 &&
        newPwdController.text.length >= 6 &&
        newPwdConfirmController.text.length >= 6) {
      isAsh.value = false;
      return;
    }
    isAsh.value = true;
  }
}
